
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, { useContext, useState } from 'react'
import '../../scss/use/window.scss'
import { Button, Form, Input } from 'antd';
import 'antd/dist/antd.min.css'
import '../../scss/use/window.scss'
import ThemeContext from '../public/ThemContext';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const { TextArea } = Input;


const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
export default function EditMessage() {
    let nickname1 = sessionStorage.getItem('nickname') as any
    let textA = sessionStorage.getItem('selfinTroduction') as any

    const [name, setName] = useState<string>(nickname1);
    const [text, setText] = useState<string>(textA);
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const navigate = useNavigate();

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(url);
                // console.log(info.file.response.data.url)
                //存储图片地址
                sessionStorage.setItem('avatar', info.file.response.data.url)
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    const onFinish = (values: any) => {
        //提交可获得数据
        console.log('Success:', values);
        //将修改后的签名和用户名保存到客户端,并更新数据表中的数据
        let nickname = values.username;
        let selfinTroduction = values.textarea;
        //获取sessionStorage中保存的uid
        const uid = sessionStorage.getItem('uid')
        const avatar = sessionStorage.getItem('avatar')
        axios.post('http://127.0.0.1:81/pesonInfo', {
            params: { uid, nickname, selfinTroduction, avatar }
        }).then((res) => {
            if (res.status == 200) {
                message.success(res.data.msg)
                //退出登录并跳转到登录页面
                //清除缓存
                sessionStorage.clear()
                //跳转到登录页面
                navigate({ pathname: '/' })
            }
            // console.log(res)
        }).catch((error) => {
            console.log(error)
        })
    };

    // 接收传过来的值
    let { operate } = useContext(ThemeContext);

    return (
        <div style={{ display: (operate === '资料' ? 'block' : 'none') }}>
            <div>
                <div className='upAvatar'>
                    <Upload
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action=" http://127.0.0.1:81/upload"
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                    </Upload>
                </div>
                <Form
                    layout="horizontal"
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                >
                    <Form.Item name="username">
                        <Input size='large' placeholder={name} onChange={(e) => { setName(e.target.value) }} />
                    </Form.Item>
                    <Form.Item name='textarea'>
                        <TextArea placeholder={text} rows={4} onChange={(e) => { setText(e.target.value) }} />
                    </Form.Item>
                    <Form.Item>
                        <Button size='large' type="primary" htmlType="submit" block >确定</Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
